﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;
using Microsoft.Win32;
using AssociationManager;
using System.Net;
using System.Threading;
using PS3Helpers;
using PS3Packager.UserControls;

namespace PS3Packager
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            newToolStripMenuItem.PerformClick();

            UpdateFileAssociations();

            
            // Hide functionality not available yet. This was functionality added at an early stage before the PS3 Visual Studio add-in was created.
            uploadPackageToolStripMenuItem.Visible = false;
            copyPackageToolStripMenuItem.Visible = false;
            toolStripSeparator2.Visible = false;
            buildToolStripMenuItem.Visible = false;
        }

        internal void LoadFile(string filename)
        {
            try
            {
                p3PEditor.PackageFile = new PS3PackageFile(filename);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to read file!\r\nError message: " + ex.Message, "Read failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            UpdateTitle();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            p3PEditor.PackageFile = new PS3PackageFile();
            UpdateTitle();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.CheckFileExists = true;
            ofd.Filter = "PS3 Packager File|*.p3p|All Files|*.*";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                LoadFile(ofd.FileName);
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string filename = p3PEditor.PackageFile.Filename;
            if (string.IsNullOrEmpty(filename))
            {
                saveAsToolStripMenuItem.PerformClick();
                return;
            }

            SaveFile(filename);
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.CheckPathExists = true;
            sfd.Filter = "PS3 Packager File|*.p3p|All Files|*.*";

            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SaveFile(sfd.FileName);
            }
        }

        private void SaveFile(string filename)
        {
            try
            {
                PS3PackageFile packagefile = p3PEditor.PackageFile;
                packagefile.SaveFile(filename);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to save file!\r\nError message: " + ex.Message, "Save failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            UpdateTitle();
        }

        private void UpdateTitle()
        {
            string filename = string.IsNullOrEmpty(p3PEditor.PackageFile.Filename) ? "New File" : p3PEditor.PackageFile.Filename;
            this.Text = Application.ProductName + " - " + filename;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buildGeneratePkgFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreatePkgFile(true);
        }

        private void generatePkgFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreatePkgFile(false);
        }

        private void CreatePkgFile(bool buildfirst)
        {
            PS3PackageFile packagefile = p3PEditor.PackageFile;

            CompilationProgressForm frm = new CompilationProgressForm();

            PackageGeneratorThread genthread = new PackageGeneratorThread(frm, buildfirst, packagefile);
            frm.ShowDialog(genthread, packagefile);
        }

        private void uploadPackageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UploadToPS3Form frm = new UploadToPS3Form();
            frm.UriStr = Properties.Settings.Default.PS3FtpUri;
            frm.LocalPackageFile = @"C:\Development\PS3 Packager\PS3Packager\Samples\666402-4E0357458_00-PS3SCENEF9CCAA0B.pkg";

            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // UploadPackageToPS3(frm.FtpUri, frm.LocalPackageFile);
                CompilationProgressForm progressfrm = new CompilationProgressForm();
                PackageUploadThread uploadthread = new PackageUploadThread(progressfrm, frm.LocalPackageFile, frm.FtpUri);

                PS3PackageFile packagefile = p3PEditor.PackageFile;
                progressfrm.ShowDialog(uploadthread, packagefile);
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("PS3 pkg creator by rfc1459", "About");
        }

        private void importSFOFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.CheckFileExists = true;
            ofd.Filter = "PS3 SFO File|*.sfo|All Files|*.*";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    PS3SFO sfo = new PS3SFO(ofd.FileName);

                    PS3PackageFile packagefile = p3PEditor.PackageFile;
                    packagefile.Title = sfo.Title;
                    packagefile.Category = sfo.Category;
                    packagefile.ContentId = sfo.TitleId;
                    packagefile.AppVer = sfo.ApplicationVersion;


                    packagefile.ParentalLockLevel = sfo.ParentalLevel;


                    packagefile.VideoResolution = sfo.VideoResolution;
                    packagefile.AudioFormat = sfo.AudioFormat;

                    // Update changes to package file...
                    p3PEditor.PackageFile = packagefile;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to read file!\r\nError message: " + ex.Message, "Read failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void exportSFOFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.CheckPathExists = true;
            sfd.Filter = "PS3 SFO File|*.sfo|All Files|*.*";

            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                PS3SFO sfo = new PS3SFO(true);

                PS3PackageFile packagefile = p3PEditor.PackageFile;
                sfo.Title = packagefile.Title;
                sfo.Category = packagefile.Category;
                sfo.TitleId = packagefile.ContentId;
                sfo.ApplicationVersion = packagefile.AppVer;


                sfo.ParentalLevel = packagefile.ParentalLockLevel;


                sfo.VideoResolution = packagefile.VideoResolution;
                sfo.AudioFormat = packagefile.AudioFormat;

                sfo.SaveFile(sfd.FileName);
            }
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OptionsForm frm = new OptionsForm();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                UpdateFileAssociations();
            }
        }

        private void UpdateFileAssociations()
        {
            using (FileAssociationManager mgr = new FileAssociationManager())
            {
                if (Properties.Settings.Default.MaintainP3PFileAssociations)
                {
                    using (ApplicationAssociation ext = mgr.RegisterFileAssociation("p3p"))
                    {
                        ext.DefaultIcon = new ApplicationIcon(Application.ExecutablePath);
                        ext.ShellOpenCommand = Application.ExecutablePath;
                        ext.Associated = true;

                        using (ShellCommand cmd = ext.RegisterShellCommand("BuildPS3Package", "Build PS3 Package"))
                        {
                            cmd.Command = Application.ExecutablePath + " -build";
                        }
                    }

                    using (ShellCommand cmd = mgr.RegisterDirectoryShellCommand("CreatePS3Package", "Create PS3 Package Project"))
                    {
                        cmd.Command = Application.ExecutablePath + " -createproject";
                    }
                }
                else
                {
                    mgr.UnregisterApplicationAssociation();
                }
            }
        }
    }
}
